package Servlet.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import CodeAdmin.Code;
import Form.CodeForm;

@SuppressWarnings("serial")
public class CodeServlet extends HttpServlet {

	public static final String VUE = "/WEB-INF/code.jsp";
	public static final String CODE = "code";
	public static final String FORM = "form";
    
	private static final String CHAMP_EMAIL = "email";
	
	
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
    		throws ServletException, IOException {
    	
        /* Affichage de la page code */
        this.getServletContext().getRequestDispatcher( VUE ).forward(req, resp);
    }
    
    
    public void doPost(HttpServletRequest req, HttpServletResponse resp) 
    		throws ServletException, IOException {
    	
    	String bouton1 = req.getParameter("valStatut");
    	String bouton2 = req.getParameter("valMail");
    	
    	req.getSession().setAttribute("bouton1", bouton1);
    	req.getSession().setAttribute("bouton2", bouton2);
    	
    	CodeForm form = new CodeForm();
    	Code code = null;
    	
    	/**
    	 * On regarde sur quel bouton a cliqué l'administrateur
    	 * et on réalise l'action associée dans le cas échéant 
    	 */
    	if (bouton1 != null) {
    		code = form.genCode(req,code);
    		req.getSession().setAttribute(CODE, code);
    	}
    	
    	if (bouton2 != null) {
    		try {
    			code = (Code) req.getSession().getAttribute(CODE);
    			form.sendCode(req,code.getCode());
    			
    		} catch (Exception e) {
                form.getErreurs().put(CHAMP_EMAIL, "Veuillez créer un code");
                form.setResultat("Echec de l'envoi du mail");
            }
    	}
        
        req.setAttribute(FORM, form);
        
        /* Transmission de la paire d'objets request/response à notre JSP */
        this.getServletContext().getRequestDispatcher( VUE ).forward(req, resp);
    }
}